﻿#region Usings

using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using Rail.Net.Common.ActionFilters;

#endregion

namespace Rail.Net.Controllers
{
    [SetCulture]
    public abstract class BaseController : AsyncController
    {
        private Cache _cache;

        public Cache Cache
        {
            get
            {
                if (_cache != null)
                {
                    return _cache;
                }
                _cache = HttpRuntime.Cache;
                return _cache;
            }
        }

        protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);

                return sw.GetStringBuilder().ToString();
            }
        }

        public static string ConvertToUtf8(string toBeConverted)
        {
            var iso88591 = Encoding.GetEncoding("iso-8859-1");
            var utf8 = Encoding.UTF8;

            var isoBytes = iso88591.GetBytes(toBeConverted);
            var utf8Bytes = Encoding.Convert(iso88591, utf8, isoBytes);

            return utf8.GetString(utf8Bytes);
        }

        #region Culture manipulation

        public ActionResult SetCulture(string id)
        {
            var userCookie = Request.Cookies["Culture"];

            if (userCookie != null)
            {
                userCookie.Value = id;
                userCookie.Expires = DateTime.Now.AddYears(100);
                Response.SetCookie(userCookie);
            }

            return Redirect(Request.UrlReferrer.ToString());
        }

        #endregion
    }
}